<?php

namespace App\Kuafu\Export\Command;

use App\Kuafu\Export\Model\ExportDownloadModel;
use App\Kuafu\Nsq\Enum\NsqCodeEnum;
use App\Kuafu\User\Model\User;
use App\Library\FeiShu\SendFs;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Kuafu\GeneralFs\BuildFs;
use Kuafu\Nsq\NsqSubscriber;
use NSQClient\Contract\Message;

class NsqSubExportDownload extends Command
{
    protected $signature = 'export:nsq-sub-export-download';

    protected $description = 'NSQ接受导出下载处理';

    public function handle()
    {
        ini_set('memory_limit', '2G');

        (new NsqSubscriber(config('nsq.default.address')))
            ->sub(NsqCodeEnum::EXPORT_DOWNLOAD, NsqCodeEnum::EXPORT_DOWNLOAD_CHANNEL,
                function (Message $message) {
                    $data = $message->data();

                    // 参数校验
                    if (!$this->valid($data)) {
                        $message->done();
                        return;
                    }

                    // 执行
                    $this->process($data);

                    $message->done();
                }
            );
    }

    private function valid(array $data): bool
    {
        $validator = Validator::make($data, [
            'userId'       => 'required|integer|min:1',
            'name'         => 'required|string',
            'path'         => 'required|string',
            'startTime'    => 'required|integer|min:1',
            'completeTime' => 'required|integer|min:1',
            'status'       => 'required|integer|min:0',
            'client'       => 'required|integer|min:0',
            'fileType'     => 'required|integer|min:0',
            'fileTypeText' => 'required|string',
            'params'       => 'required|string',
            'sendRobot'    => 'required|integer|min:0|max:1',
        ]);

        if ($validator->fails()) {
            Log::warning("NsqSubExportDownload valid error:" . $validator->errors()->first(), $data);
            return false;
        }

        return true;
    }

    private function process(array $data): void
    {
//        $struct = [
//            'userId'       => 1,
//            'name'         => '0001-堂食菜品销售_2022-10-01-2022-12-01_13:51:12',
//            // 具体的文件名，自定义
//            'path'         => '90/3d/465a08bc2c20c84 a4886c3b500cb7d10e50d01e41961918f576a62c62354.csv',
//            // oss path
//            'startTime'    => 1689318818,
//            // 开始时间
//            'completeTime' => 1689318818,
//            // 完成时间
//            'status'       => '',
//            // 1导出中 2导出完成
//            'client'       => 1,
//            // 1web 2app
//            'fileType'     => 0,
//            // 默认给0吧,
//            'fileTypeText' => '堂食订单明细',
//            // 业务类型，给中文
//            'params'       => '{"endAt": "2022-12-01", "shopId": 1, "source": 1, "startAt": "2022-10-01"}',
//            // json格式的参数，留痕
//            'sendRobot'    => 1,
//            // 发送机器人消息
//        ];

        ExportDownloadModel::query()->insert([
            'createdByUid' => $data['userId'],
            'updatedByUid' => $data['userId'],
            'createdAt'    => time(),
            'updatedAt'    => time(),
            'name'         => $data['name'],
            'path'         => $data['path'],
            'ext'          => pathinfo($data['path'], PATHINFO_EXTENSION),
            'startTime'    => $data['startTime'],
            'completeTime' => $data['completeTime'],
            'expireTime'   => time() + 30 * 86400,
            'status'       => $data['status'],
            'client'       => $data['client'],
            'fileType'     => $data['fileType'],
            'fileTypeText' => $data['fileTypeText'],
            'params'       => $data['params'],
        ]);

        try {
            // 发送机器人消息
            if ($data['sendRobot']) {

                $user = User::query()->where('id', $data['userId'])->first();
                if ($user) {

                    $feishuId = $user->feishuUserId;
                    $this->userName = $user->username;

                    $this->excelUrl      = "https://file.51kuafu.com/" . $data['path'];
                    $this->excelName     = $data['name'];
                    $this->startDateTime = date('Y-m-d H:i:s', $data['startTime']);
                    $this->endDateTime   = date('Y-m-d H:i:s', $data['completeTime']);

                    BuildFs::newRobot('center', BuildFs::MSG_TYPE_CARD, BuildFs::MODULE_TYPE_APP)
                           ->setCardContent($this->template())
                           ->setFeishuId($feishuId)
                           ->send();
                }
            }
        } catch (\Exception $e) {
            Log::warning($e);
        }
    }

    private string $excelName;
    private string $excelUrl;
    private string $startDateTime;
    private string $endDateTime;
    private string $userName;

    private function template(): array
    {
        return array (
            'config' =>
                array (
                    'wide_screen_mode' => true,
                ),
            'header' =>
                array (
                    'template' => 'blue',
                    'title' =>
                        array (
                            'content' => '报表下载成功',
                            'tag' => 'plain_text',
                        ),
                ),
            'elements' =>
                array (
                    0 =>
                        array (
                            'fields' =>
                                array (
                                    0 =>
                                        array (
                                            'is_short' => true,
                                            'text' =>
                                                array (
                                                    'content' => '**报表名称：**
'.$this->excelName,
                                                    'tag' => 'lark_md',
                                                ),
                                        ),
                                    1 =>
                                        array (
                                            'is_short' => true,
                                            'text' =>
                                                array (
                                                    'content' => '**用户名称：**
'.$this->userName,
                                                    'tag' => 'lark_md',
                                                ),
                                        ),
                                    2 =>
                                        array (
                                            'is_short' => false,
                                            'text' =>
                                                array (
                                                    'content' => '',
                                                    'tag' => 'lark_md',
                                                ),
                                        ),
                                    3 =>
                                        array (
                                            'is_short' => true,
                                            'text' =>
                                                array (
                                                    'content' => '**开始时间：**
'.$this->startDateTime,
                                                    'tag' => 'lark_md',
                                                ),
                                        ),
                                    4 =>
                                        array (
                                            'is_short' => true,
                                            'text' =>
                                                array (
                                                    'content' => '**完成时间：**
'.$this->endDateTime,
                                                    'tag' => 'lark_md',
                                                ),
                                        ),
                                    5 =>
                                        array (
                                            'is_short' => false,
                                            'text' =>
                                                array (
                                                    'content' => '',
                                                    'tag' => 'lark_md',
                                                ),
                                        ),
                                ),
                            'tag' => 'div',
                        ),
                    1 =>
                        array (
                            'tag' => 'hr',
                        ),
                    2 =>
                        array (
                            'actions' =>
                                array (
                                    0 =>
                                        array (
                                            'tag' => 'button',
                                            'text' =>
                                                array (
                                                    'content' => '点我下载',
                                                    'tag' => 'plain_text',
                                                ),
                                            'type' => 'primary',
                                            'value' =>
                                                array (
                                                    'chosen' => 'approve',
                                                ),
                                            'url' => $this->excelUrl,
                                        ),
                                ),
                            'layout' => 'bisected',
                            'tag' => 'action',
                        ),
                ),
        );
    }
}
